package com.tbq.game.service.app.mvp

import android.Manifest
import android.app.Activity
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.PermissionChecker
import com.tbq.game.service.app.App
import java.util.*

abstract class BaseActivity<V : IBaseView, P : BasePresenter<V>>(private var layoutID: Int) : AppCompatActivity(),
    IBaseView {

    companion object {
        private val startCalendar = Calendar.getInstance()
        val startYear = startCalendar.get(Calendar.YEAR)
        val startMonth = startCalendar.get(Calendar.MONTH)
        val startDay = startCalendar.get(Calendar.DAY_OF_MONTH)
    }

    protected var mPresenter: P? = null
    private var TAG: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (layoutID != 0)
            setContentView(layoutID)
        if (mPresenter == null)
            mPresenter = createPresenter()
        mPresenter?.attach(this as V)
        supportActionBar?.setHomeButtonEnabled(true)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        App.context?.addActivity(this)
        getApprove()
        onInitViewsAndData()
    }
    abstract fun onInitViewsAndData()
    protected abstract fun createPresenter(): P

    private val LOCATIONGPS = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE)
    private  fun getApprove() {
        if (Build.VERSION.SDK_INT >= 23) { //判断是否为android6.0系统版本，如果是，需要动态添加权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PermissionChecker.PERMISSION_GRANTED
            ) {// 没有权限，申请权限。
                ActivityCompat.requestPermissions(this, LOCATIONGPS,
                    100)//100定位权限请求
            }
        }
    }
    //这个onWindowFocusChanged指的是这个Activity得到或者失去焦点的时候 就会call
    private var isDrawFinish = false
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus && !isDrawFinish) {
            isDrawFinish = true
            onDrawFinish()
        }

    }
    open fun onDrawFinish() {
        //绘制完成界面
    }
    override fun onDestroy() {
        super.onDestroy()
        if (mPresenter != null)
            mPresenter?.dettach()
    }
}